<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    echo "<script>alert('请先登录！');window.location.href='login.php';</script>";
    exit;
}
require_once 'conn.php'; // 数据库连接

// 判断是否登录
if (!isset($_SESSION['user_id'])) {
    echo "<script>alert('请先登录！');window.location.href='login.php';</script>";
    exit;
}

// 获取表单提交的数据
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
$user_id = intval($_SESSION['user_id']); // 从 session 获取用户 id

if ($product_id > 0 && $quantity > 0) {
    // 查询商品价格和库存
    $sql = "SELECT price, stock FROM products WHERE id = $product_id";
    $result = mysqli_query($conn, $sql);

    if ($result && mysqli_num_rows($result) > 0) {
        $product = mysqli_fetch_assoc($result);

        // 判断库存
        if ($quantity > intval($product['stock'])) {
            echo "<script>alert('库存不足');window.history.back();</script>";
            exit;
        }

        $total = $product['price'] * $quantity;

        // 查询该商品是否已经在购物车中
        $check_sql = "SELECT id, quantity FROM cart WHERE product_id = $product_id AND user_id = $user_id";
        $check_result = mysqli_query($conn, $check_sql);

        if (mysqli_num_rows($check_result) > 0) {
            // 如果该商品已经在购物车中，更新数量和总金额
            $cart_item = mysqli_fetch_assoc($check_result);
            $new_quantity = $cart_item['quantity'] + $quantity;
            $new_total = $product['price'] * $new_quantity;

            $update_sql = "UPDATE cart SET quantity = $new_quantity, total = $new_total WHERE id = " . $cart_item['id'];
            if (mysqli_query($conn, $update_sql)) {
                echo "<script>alert('购物车更新成功');window.location.href='cart.php';</script>";
            } else {
                echo "<script>alert('更新购物车失败');window.history.back();</script>";
            }
        } else {
            // 如果该商品不在购物车中，插入新记录
            $date = date("Y-m-d H:i:s");
            $insert_sql = "INSERT INTO cart (product_id, user_id, quantity, total, date) 
                           VALUES ($product_id, $user_id, $quantity, $total, '$date')";

            if (mysqli_query($conn, $insert_sql)) {
                echo "<script>alert('加入购物车成功');window.location.href='cart.php';</script>";
            } else {
                echo "<script>alert('加入购物车失败');window.history.back();</script>";
            }
        }
    } else {
        echo "<script>alert('商品不存在');window.history.back();</script>";
    }
} else {
    echo "<script>alert('数据不合法');window.history.back();</script>";
}

mysqli_close($conn);
